﻿/*
 * Сделано в SharpDevelop.
 * Пользователь: Eugenij
 * Дата: 29.01.2014
 * Время: 17:54
 * 
 * Для изменения этого шаблона используйте Сервис | Настройка | Кодирование | Правка стандартных заголовков.
 */
using System;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;

namespace hwspeed
{
    /// <summary>
    /// Description of fmIndicator.
    /// </summary>
    public partial class fmIndicator : Form
    {
        public fmIndicator()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
            Icon = Configuration.MainIcon;
            //try { modemchik = new Modem(Configuration.SelectedModem); } catch (Exception){}
            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }
        
        void Timer1Tick(object sender, EventArgs e)
        {
            DBMS.Text = dbval;
            SRCD.Text = dbsrc;
        }
        
        volatile Thread indicate = null;
        volatile string dbval = "";
        volatile string dbsrc = "";
        
        static volatile bool isClosing = false;
        
        void FmIndicatorShown(object sender, EventArgs e)
        {
            if (indicate == null){
                isClosing = false;
                indicate = new Thread(Indicate);
                indicate.Start();
            }
        }
        
        void FmIndicatorFormClosing(object sender, FormClosingEventArgs e)
        {
            isClosing = true;
            indicate.Join();
            indicate = null;
        }
        
        void FmIndicatorLoad(object sender, EventArgs e)
        {
        }
        
        void Indicate()
        {
            Modem modemchik = new Modem(Configuration.SelectedModem);
            if (modemchik != null)
            {
                do {
                    try {
                        //Debug.WriteLine("ats");
                        string src = Modem.atBody(modemchik.AtCmd("AT+CSQ"));
                        //Debug.WriteLine("atr");
                        var r = new Regex(@"^\+CSQ:\s+(.+)$", RegexOptions.IgnoreCase);
                        var mt = r.Match(src);
                        if (mt.Groups.Count > 1)
                        {
                            dbval = ((double.Parse(mt.Groups[1].Value)*2)-113).ToString();
                            dbsrc = mt.Groups[1].Value;
                        }
                    } catch (Exception){}
                    if (isClosing) break;
                    Thread.Sleep(500);
                } while (isClosing == false);
                modemchik.Reset();
            }
        }
    }
}
